<template>
  <div class="sale-management">
    <div class="page-header">
      <h1>销售管理</h1>
      <el-button type="primary" @click="openAddDialog" :icon="Plus">添加销售记录</el-button>
    </div>
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-row :gutter="10" class="mb-20">
        <el-col :span="6">
          <el-input v-model="searchForm.keyword" placeholder="请输入销售ID、顾客姓名或产品名称搜索" :prefix-icon="Search"
                    @keyup.enter="handleSearch">
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 销售记录表格 -->
    <el-card class="sales-table-card">
      <el-table
          :data="sales"
          stripe
          style="width: 100%"
          v-loading="loading"
          border
      >
        <el-table-column prop="sid" label="销售ID" width="120" />
        <el-table-column prop="cname" label="顾客姓名" width="120" />
        <el-table-column prop="pname" label="产品名称" width="120" />
        <el-table-column prop="price" label="单价" width="100" :formatter="(row, column) => `¥${row.price.toFixed(2)}`" />
        <el-table-column prop="count" label="数量" width="80" />
        <el-table-column prop="total" label="总价" width="100" :formatter="(row, column) => `¥${row.total.toFixed(2)}`" />
        <el-table-column prop="saleDate" label="销售日期" width="140" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditDialog(scope.row.sid)" :icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteSale(scope.row.sid)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑销售记录对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditing? '编辑销售记录' : '添加销售记录'"
        width="500px"
        center
    >
      <el-form
          ref="formRef"
          :model="formData"
          label-width="100px"
          class="form-container"
      >
        <el-form-item label="销售ID">
          <el-input v-model="formData.sid" disabled />
        </el-form-item>
        <el-form-item label="顾客">
          <el-select v-model="formData.cid" placeholder="请选择顾客" style="width: 100%">
            <el-option v-for="item in customers" :key="item.cid" :label="item.name" :value="item.cid" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="formData.pid" placeholder="请选择产品" style="width: 100%" @change="loadProductPrice">
            <el-option v-for="item in products" :key="item.pid" :label="item.name" :value="item.pid" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="formData.count" :min="1" @change="calculateTotal" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="formData.price" type="number" placeholder="请输入单价" @change="calculateTotal" />
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="formData.total" disabled />
        </el-form-item>
        <el-form-item label="销售日期">
          <el-date-picker
              v-model="formData.saleDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSale">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { ElMessageBox, ElNotification } from 'element-plus';
import {
  Plus,
  Edit,
  Delete,
  Search
} from '@element-plus/icons-vue';

// 模拟销售数据 - 实际项目中应通过API获取
const sales = ref([
  { sid: 'S001', cid: 'C001', cname: '张三', pid: 'P001', pname: '玫瑰', price: 15.00, count: 2, total: 30.00, saleDate: '2025-06-25' },
  { sid: 'S002', cid: 'C002', cname: '李四', pid: 'P002', pname: '百合', price: 20.00, count: 1, total: 20.00, saleDate: '2025-06-26' },
  { sid: 'S003', cid: 'C003', cname: '王五', pid: 'P003', pname: '康乃馨', price: 12.00, count: 3, total: 36.00, saleDate: '2025-06-27' },
  { sid: 'S004', cid: 'C001', cname: '张三', pid: 'P004', pname: '郁金香', price: 18.00, count: 2, total: 36.00, saleDate: '2025-06-28' },
  { sid: 'S005', cid: 'C004', cname: '赵六', pid: 'P002', pname: '百合', price: 20.00, count: 2, total: 40.00, saleDate: '2025-06-29' }
]);

// 模拟顾客数据 - 实际项目中应通过API获取
const customers = ref([
  { cid: 'C001', name: '张三' },
  { cid: 'C002', name: '李四' },
  { cid: 'C003', name: '王五' },
  { cid: 'C004', name: '赵六' },
  { cid: 'C005', name: '钱七' }
]);

// 模拟产品数据 - 实际项目中应通过API获取
const products = ref([
  { pid: 'P001', name: '玫瑰', price: 15.00 },
  { pid: 'P002', name: '百合', price: 20.00 },
  { pid: 'P003', name: '康乃馨', price: 12.00 },
  { pid: 'P004', name: '郁金香', price: 18.00 },
  { pid: 'P005', name: '向日葵', price: 25.00 }
]);

// 搜索条件
const searchForm = reactive({
  keyword: ''
});

// 表单数据 - 添加/编辑销售记录
const formData = reactive({
  sid: '',
  cid: '',
  pid: '',
  count: 1,
  price: 0,
  total: 0,
  saleDate: new Date().toISOString().split('T')[0]
});

// 控制对话框显示
const dialogVisible = ref(false);
const isEditing = ref(false);
const currentId = ref('');
// 加载状态（示例中未实际使用，可按需补充逻辑）
const loading = ref(false);

// 页面加载时获取数据
onMounted(() => {
  // 实际项目中这里应该调用API获取数据
  console.log('销售列表页面已加载');
});

// 打开添加对话框
const openAddDialog = () => {
  resetForm();
  dialogVisible.value = true;
  isEditing.value = false;
};

// 打开编辑对话框
const openEditDialog = (id) => {
  const sale = sales.value.find(item => item.sid === id);
  if (sale) {
    resetForm();
    formData.sid = sale.sid;
    formData.cid = sale.cid;
    formData.pid = sale.pid;
    formData.count = sale.count;
    formData.price = sale.price;
    formData.total = sale.total;
    formData.saleDate = sale.saleDate;
    dialogVisible.value = true;
    isEditing.value = true;
    currentId.value = id;
  }
};

// 重置表单
const resetForm = () => {
  formData.sid = '';
  formData.cid = '';
  formData.pid = '';
  formData.count = 1;
  formData.price = 0;
  formData.total = 0;
  formData.saleDate = new Date().toISOString().split('T')[0];
};

// 计算总价
const calculateTotal = () => {
  formData.total = formData.price * formData.count;
};

// 保存销售记录
const saveSale = () => {
  // 简单验证
  if (!formData.cid || !formData.pid || formData.count <= 0 || formData.price <= 0) {
    ElMessageBox.alert('请填写完整的销售信息', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }

  // 模拟保存逻辑 - 实际项目中应调用API
  if (isEditing.value) {
    // 编辑现有记录
    const index = sales.value.findIndex(item => item.sid === currentId.value);
    if (index!== -1) {
      sales.value[index] = {
        ...sales.value[index],
        cid: formData.cid,
        pid: formData.pid,
        count: formData.count,
        price: formData.price,
        total: formData.total,
        saleDate: formData.saleDate,
        // 添加顾客和产品名称用于显示
        cname: customers.value.find(c => c.cid === formData.cid)?.name || '未知顾客',
        pname: products.value.find(p => p.pid === formData.pid)?.name || '未知产品'
      };
      ElNotification({
        title: '成功',
        message: '销售记录更新成功',
        type: 'success',
        duration: 3000
      });
    }
  } else {
    // 添加新记录
    // 生成新的销售ID - 实际项目中可能由后端生成
    const newId = 'S' + (sales.value.length + 1001).toString().substring(1);
    const newSale = {
      sid: newId,
      cid: formData.cid,
      pid: formData.pid,
      count: formData.count,
      price: formData.price,
      total: formData.total,
      saleDate: formData.saleDate,
      // 添加顾客和产品名称用于显示
      cname: customers.value.find(c => c.cid === formData.cid)?.name || '未知顾客',
      pname: products.value.find(p => p.pid === formData.pid)?.name || '未知产品'
    };
    sales.value.unshift(newSale);
    ElNotification({
      title: '成功',
      message: '新销售记录添加成功',
      type: 'success',
      duration: 3000
    });
  }

  dialogVisible.value = false;
};

// 删除销售记录
const deleteSale = (id) => {
  ElMessageBox.confirm('确认删除这条销售记录吗？此操作不可恢复。', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除逻辑 - 实际项目中应调用API
    sales.value = sales.value.filter(item => item.sid!== id);
    ElNotification({
      title: '成功',
      message: '销售记录删除成功',
      type: 'success',
      duration: 3000
    });
  }).catch(() => {
    // 取消删除
  });
};

// 搜索功能
const handleSearch = () => {
  if (!searchForm.keyword) {
    // 如果搜索框为空，显示全部数据
    // 实际项目中可能需要调用API获取全部数据
    return;
  }

  // 模拟搜索逻辑 - 实际项目中应调用带参数的API
  const keyword = searchForm.keyword.toLowerCase();
  sales.value = sales.value.filter(item =>
      item.sid.toLowerCase().includes(keyword) ||
      item.cname.toLowerCase().includes(keyword) ||
      item.pname.toLowerCase().includes(keyword)
  );
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  // 实际项目中这里应该重新获取全部数据
  handleSearch();
};
</script>

<style scoped>
.sale-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card,
.sales-table-card {
  margin-bottom: 20px;
}

.form-container {
  width: 100%;
}
</style>